package com.wedistudio.slideshare.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simpleframework.xml.Serializer;

import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.pool.PoolFactory;
import com.wedistudio.android.framework.service.Service;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.android.framework.service.ServiceRequestConverter;
import com.wedistudio.android.framework.service.ServiceResponseConverter;
import com.wedistudio.slideshare.SlideshareUtils;
import com.wedistudio.slideshare.xml.Slideshow;
import com.wedistudio.slideshare.xml.TagSearch;
import com.wedistudio.slidesprovider.SearchWindow;
import com.wedistudio.slidesprovider.Slide;
import com.wedistudio.slidesprovider.SlideTag;
import com.wedistudio.slidesprovider.Slides;

public class GetSlidesFromTag extends Service<SearchWindow<SlideTag>, Slides> {
	static public GetSlidesFromTag create() {
		return new GetSlidesFromTag();
	}

	private static String GET_SLIDESHOW_BY_TAG = "get_slideshows_by_tag";

	private GetSlidesFromTag() {

		setRequestConverter(new ServiceRequestConverter<SearchWindow<SlideTag>>() {

			@Override
			public List<URLParams> convert(SearchWindow<SlideTag> request)
					throws ServiceException {
				List<URLParams> result = new ArrayList<URLParams>();
				URLParams params = SlideshareUtils
						.buildURLParams(GET_SLIDESHOW_BY_TAG);

				params.addParam("tag", request.getObj().getTag());
				params.addParam("detailed", "1");
				params.addParam("offset", "" + request.getLimit());
				params.addParam("limit", "" + request.getOffset());
				result.add(params);
				return result;
			}
		});

		setResponseConverter(new ServiceResponseConverter<Slides>() {

			@Override
			public Slides convert(Map<URLParams, String> raw)
					throws ServiceException {
				Serializer serializer = null;
				try {
					String xml = null;
					Integer offset = 0;
					for (Map.Entry<URLParams, String> entry : raw.entrySet()) {
						xml = entry.getValue();
						SlideshareUtils.checkResponse(xml);
						offset = Integer.parseInt(entry.getKey().getParams()
								.get("offset"));
					}

					serializer = PoolFactory.get(Serializer.class);

					final TagSearch tag = serializer.read(TagSearch.class, xml);

					Slides result = new Slides("tag:" + tag.Name, tag.Count,
							offset);

					for (final Slideshow slideshow : tag.slideshows) {
						Slide slide = slideshow.getSlide();
						result.add(slide);
					}
					return result;

				} catch (ServiceException e) {
					throw e;
				} catch (Throwable e) {
					throw new ServiceException(e);
				} finally {
					PoolFactory.release(serializer, Serializer.class);
				}

			}
		});
	}
}
